package com.eascs.admin.o2o.detail.service;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.eascs.admin.common.config.FtpConfig;
import com.eascs.admin.common.service.BaseSevice;
import com.eascs.admin.common.utils.FtpNetUtils;
import com.eascs.admin.o2o.loan.dao.O2oLoanapplyDao;
import com.eascs.admin.o2o.loan.entity.O2oLoanapplyEntity;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.datalist.dao.O2oDataListDao;
import com.eascs.datalist.entity.O2oDataListEntity;
import com.eascs.file.FileTypeConstants;

@Service
public class LoanDetailService extends BaseSevice {
	private static Logger log = LoggerFactory.getLogger(LoanDetailService.class);
	@Autowired
	private O2oLoanapplyDao o2oLoanapplyDao;
	@Autowired
	private O2oDataListDao o2oDataListDao;
	/**
	 * 重新拉取中行合同
	 * @param loanapplyNo
	 * @return
	 */
	@Transactional(transactionManager = "o2oTransactionManager")
	public boolean delContract(String loanapplyNo){
		log.info("重新拉取合同,主表ID{}", loanapplyNo);
		O2oLoanapplyEntity loanapplyEntity=o2oLoanapplyDao.getById(O2oLoanapplyEntity.class, loanapplyNo);
		loanapplyEntity.setBankOsn(null);
		List<O2oDataListEntity> o2oDatalist=o2oDataListDao.findDateEntity(loanapplyNo,FileTypeConstants.DALIST_TYPE_REFUND);
		if(o2oDatalist!=null && !o2oDatalist.isEmpty()){
			for (O2oDataListEntity o2oDataListEntity : o2oDatalist) {
				boolean flag= FtpNetUtils.deleteFile(FtpConfig.ftpConfigSetting().getHref(), Integer.valueOf(FtpConfig.ftpConfigSetting().getPort()), FtpConfig.ftpConfigSetting().getUsername(), FtpConfig.ftpConfigSetting().getPassword(), o2oDataListEntity.getUrlpath());
				if(flag){
					log.info("删除FTP成功,中行合同路径{},主表ID{}", o2oDataListEntity.getUrlpath(),loanapplyNo);
					o2oDataListDao.deleteById(O2oDataListEntity.class, o2oDataListEntity.getDatalistNo());
					log.info("删除附件表成功,中行合同路径{},附件ID{}", o2oDataListEntity.getUrlpath(),o2oDataListEntity.getDatalistNo());
				}
			}
			o2oLoanapplyDao.updateById(loanapplyEntity);
			log.info("重新拉取成功,主表ID{}", loanapplyNo);
			return true;
		}else{
			log.info("重新拉取失败,主表ID{},该单无中行合同附件", loanapplyNo);
			return false;
		}
	}
	
	public O2oLoanapplyEntity queryLoanapplyBillCode(String loanapplyNo,String loanId,String billCode,Date createDate){
		log.info("查询新系统上笔贷款编号,主表loanapplyNo：{}", loanapplyNo);
		O2oLoanapplyEntity loanapply=null;	
		List<O2oLoanapplyEntity> newloanapplyList=o2oLoanapplyDao.queryLoanId(loanapplyNo, loanId,createDate);
		if(null!=newloanapplyList && !newloanapplyList.isEmpty()){
			loanapply=newloanapplyList.get(0);
		}
		return loanapply;
	}
	
}
